package com.example.demo.pdf;

import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/export")
public class TestController {


    @RequestMapping("/exportPdf")
    public void exportPdf(HttpServletResponse response,String aaaaa) throws Exception{
        ByteArrayOutputStream baos = null;
        OutputStream out = null;
        try {

            Map<String,Object> data = new HashMap<>();
            data.put("cover", "");
            data.put("content", "");

            baos = PDFTemplateUtil.createPDF(data, "purchaseLog.ftl");;

//            // 把生成的pdf文件流压缩成文件夹
//            Map<String, ByteArrayOutputStream> byteList  = new HashMap<>();
//            byteList.put("压缩文件里面的文件名称",baos);
//            ByteArrayOutputStream byteArrayOutputStream = ZipUtils.downZipFile(byteList);

            // 设置响应消息头，告诉浏览器当前响应是一个下载文件
            response.setContentType( "application/x-msdownload");
            // 告诉浏览器，当前响应数据要求用户干预保存到文件中，以及文件名是什么 如果文件名有中文，必须URL编码
            String fileName = URLEncoder.encode("test.pdf", "UTF-8");
            response.setHeader( "Content-Disposition", "attachment;filename=" + fileName);
            out = response.getOutputStream();
            baos.writeTo(out);
            baos.close();
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("导出失败：" + e.getMessage());
        } finally{
            if(baos != null){
                baos.close();
            }
            if(out != null){
                out.close();
            }
        }
    }

    private Map<String, Object> getData(String cover,String content) {
        Map<String,Object> data = new HashMap<>();
        data.put("cover", cover);
        data.put("content", content);
        return data;
    }

}
